package fr.utt.lo02.CrazyEights.model.strategies;

import java.io.Serializable;
import java.util.Hashtable;

import fr.utt.lo02.CrazyEights.model.Game;
import fr.utt.lo02.CrazyEights.model.cards.Card;
import fr.utt.lo02.CrazyEights.model.cards.CardSuit;
import fr.utt.lo02.CrazyEights.model.players.Player;



/**
 * This strategy always try to keep a balance between the Suits
 * in the hand of the player.
 */
public class StrategyBalance implements Strategy,Serializable {

	private static final long serialVersionUID = 1L;

	/**
	 * We choose the Suit which appears the most frequently
	 * in the hand of the Player.
	 */
	public CardSuit chooseSuit(Player player) {
		Hashtable <CardSuit, Integer> hist = new Hashtable <CardSuit, Integer>();
		CardSuit suitToPlay = null;
		int nbOfThisSuit = 0;
		
		// Initializing the history table
		for(CardSuit t : CardSuit.values())
			hist.put(t, 0);

		// filling the history table
		for(Card c : player.getCardsInHand())
			hist.put(c.getSuit(), 1 + hist.get(c.getSuit())); // +1

		// finding the Suit which occurs the most
		for(CardSuit t : CardSuit.values())
			if(hist.get(t) > nbOfThisSuit) {
				nbOfThisSuit = hist.get(t);
				suitToPlay = t;
			}

		return suitToPlay;
	}

	/**
	 * We choose the Card with the Suit which appears the most
	 * frequently in the hand of the Player.
	 */
	public Card play(Player player) {
		CardSuit suitToPlay = chooseSuit(player);

			// let's play the first Card having the Suit found
			for(Card c : player.getCardsInHand())
				if(c.getSuit() == suitToPlay &&
					Game.getInstance().getDiscardPile().isPlayable(c))
					return c;

		return null;
	}
}
